package com.hybao.filter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hybao.security.AuthHandler;
import com.hybao.security.LoginUser;
import com.hybao.security.SecurityContextHolder;

public class CheckLoginFilter implements Filter{
	protected FilterConfig filterConfig = null; 
	
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{
		HttpServletRequest servletRequest = (HttpServletRequest) request;  
	    HttpServletResponse servletResponse = (HttpServletResponse) response;
	    String url = servletRequest.getRequestURI();
	    if(url.split("/").length > 1){
	    	if(url.split("/")[1].equals("login")){
	    		chain.doFilter(servletRequest, servletResponse);
	    		return;
	    	}
	    	else if(url.split("/")[1].equals("register")){
	    		chain.doFilter(servletRequest, servletResponse);
	    		return;
	    	}
	    }
	    LoginUser user = AuthHandler.getUserFromCookie(servletRequest);
	    if(user == null){
	    	servletResponse.sendRedirect("/");
			return;
	    }
	    else{
	    	if(SecurityContextHolder.getContext() != null){
	    		Map<String,Object> contextMap = SecurityContextHolder.getContext();
	    		if(contextMap != null){
	    			if(contextMap.get("loginUser") == null){
	    				contextMap.put("loginUser", user);
	    				SecurityContextHolder.setContext(contextMap);
	    			}
	    		}
	    		else{
	    			contextMap = new HashMap<String,Object>();
	    			contextMap.put("loginUser", user);
    				SecurityContextHolder.setContext(contextMap);
	    		}
	    	}
	    	else{
	    		Map<String,Object> contextMap = new HashMap<String,Object>();
    			contextMap.put("loginUser", user);
				SecurityContextHolder.setContext(contextMap);
    		}
	    }
		chain.doFilter(servletRequest, servletResponse);
	}
	
	public void destroy() {
		filterConfig = null;
	}
	
}
